#!/bin/sh

### BEGIN INIT INFO
# Provides:          intelspam
# Required-Start:    $local_fs $remote_fs $syslog $named $network $time
# Required-Stop:     $local_fs $remote_fs $syslog $named $network
# Should-Start:      $network
# Should-Stop:       $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: start and stop the Postfix IntelSpam Filter
# Description:       intelspam is a spam filter
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="Intelligent Spam Filter"
NAME="intelspam"
PROGRAMDIR="/home/kitfung/Documents/IntelSpam"
PROGRAM="$PROGRAMDIR/$NAME.pl"
PROGRAM_ARGS="mdump"
PIDFILE="/var/run/$NAME.pid"
SCRIPTNAME="/etc/init.d/$NAME"
INTELSPAM_USER="root"

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

. /lib/lsb/init-functions

do_start()
{
	start-stop-daemon --start --background --quiet --pidfile $PIDFILE --chdir $PROGRAMDIR --exec $PROGRAM \
		--chuid $INTELSPAM_USER --user $INTELSPAM_USER --test > /dev/null
   	RETVAL="$?"
	[ $RETVAL -eq 0 ] || return 1
	start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile --chdir $PROGRAMDIR --exec $PROGRAM \
      		--chuid $INTELSPAM_USER --user $INTELSPAM_USER -- $PROGRAM_ARGS
   	RETVAL="$?"

	[ $RETVAL -eq 0 ] || return 2
	
}

do_stop()
{
	start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --user $INTELSPAM_USER --pidfile $PIDFILE
   	RETVAL="$?"
	[ $RETVAL -eq 2 ] && return 2

	rm -f $PIDFILE
	RETVAL="$?"
	[ $RETVAL -eq 0 ] && return 0 || return 1
}

case "$1" in
  start)
   [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
   do_start
   case "$?" in
      0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
      2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
   esac
   ;;
  stop)
   [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
   do_stop
   case "$?" in
      0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
      2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
   esac
   ;;
  restart|force-reload)
   log_daemon_msg "Restarting $DESC" "$NAME"
   do_stop
   case "$?" in
     0|1)
      do_start
      case "$?" in
         0) log_end_msg 0 ;;
         1) log_end_msg 1 ;; # Old process is still running
         *) log_end_msg 1 ;; # Failed to start
      esac
      ;;
     *)
        # Failed to stop
      log_end_msg 1
      ;;
   esac
   ;;
  *)
   echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
   exit 3
   ;;
esac

exit 0

